import { useState, createRef, useRef, Component, useCallback } from "react";

/**
 * hooks的闭包问题
 * 当在useCallback中使用了两个异步获取数据的请求，请求完成后修改state的数据， 此时如果updateObj直接传入一个对象，会遇到值覆盖的问题，需要传入回调函数才能获取到最新值
 *
 * 请看下面的例子
 */

const fetchUser = () => {
	return new Promise((resolve) => {
		setTimeout(() => {
			resolve({ name: "popo", age: 80 });
		}, 2000);
	});
};
const fetchCount = () => {
	return new Promise((resolve) => {
		setTimeout(() => {
			resolve({ count: 8 });
		}, 3000);
	});
};

function App07() {
	const [obj, updateObj] = useState({ name: "xiaoming", age: 18, count: 0 });
	const onClick = useCallback(() => {
		fetchUser().then((user) => {
			//updateObj(user); //这样写obj的值会被覆盖
			updateObj((obj) => ({ ...obj, ...user }));
		});
		fetchCount().then((count) => {
			//updateObj(count); //这样写obj的值会被覆盖
			updateObj((obj) => ({ ...obj, ...count }));
		});
	}, []);
	return (
		<div className="App">
			<div>
				<p>name:{obj.name}</p>
				<p>age:{obj.age}</p>
				<p>count:{obj.count}</p>
				<button onClick={onClick}>请点击</button>
			</div>
		</div>
	);
}

export default App07;
